import $store from "@/store/index"


const api = {
	/**
	 * 保留小数不足补零 (2后位清除后数)
	 * */
	returnFloat(value, index = 2) {
		try {
			let num = typeof value == "number" ? JSON.stringify(value) : value;
			let s = num.toString().split('.');
			if (s.length == 1) {
				return `${num}.${''.padEnd(index, '0')}`
			} else {
				let n = s[1];
				return n.length > index ? `${s[0]}.${n.slice(0, index)}` : `${s[0]}.${n.padEnd(index, '0')}`
			}
		} catch (error) {

		}
	},
	/**
	 * 两位小数四舍五入
	 */
	returnFloatRound(value) {
		let num = this.returnFloat(value);
		num = Math.round(num * 100) * 0.01;
		return num;
	},

	/**
	 * 成功提示
	 */
	success: (msg, callfun, time) => {
		api.closeWaiting();
		time = time || 1500
		uni.showToast({
			title: msg || '操作成功',
			icon: "success",
			duration: time,
			mask: true
		})

		if (typeof callfun === "function") {
			setTimeout(() => {
				callfun();
			}, time)
		}

	},

	/**
	 * 失败提示
	 */
	error: (msg, callfun, time = 1500, mask = false) => {
		api.closeWaiting();
		uni.showToast({
			title: msg || '操作失败',
			icon: "none",
			duration: time,
			mask: mask
		})

		if (typeof callfun === "function") {
			setTimeout(() => {
				callfun();
			}, time)
		}

	},

	/**
	 * 等待层
	 */
	showWaiting: (msg) => {
		uni.showLoading({
			title: msg || '加载中',
			mask: true
		});
	},

	/**
	 * 关闭等待层
	 */
	closeWaiting: () => {
		uni.hideLoading();
	},

	/**
	 * 确认对话框
	 */
	confirm: (contents, callback, cancel) => {
		api.closeWaiting();
		uni.showModal({
			title: '提示',
			content: contents,
			success: function(res) {
				console.log(res);
				if (res.confirm) {
					callback();
				} else {
					cancel();
				}
			}
		});

	},
	/**
	 *  跳转登录
	 */
	goLogin: () => {
		// 清除用户信息
		$store.dispatch('user/removeUser');
		uni.reLaunch({
			url: '/pages/login/index'
		})
	},
	/**
	 * 修改页面名称
	 **/
	modifyHeaderTitle: (title) => {
		uni.setNavigationBarTitle({
			title: title
		})
	}
}
export default api;